package cn.ynrcb.personnelfile.common.utils;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiModelProperty;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class DeclaredFieldsUtil {
    /**
     * 根据字段获取注解值
     *
     * @param key
     * @param clazz
     * @return
     */
    public static String getName(String key, Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            // 除过fieldMap中的属性，其他属性都获取
            if (key.equals(fields[i].getName())) {
                boolean annotationPresent = fields[i].isAnnotationPresent(ApiModelProperty.class);
                if (annotationPresent) {
                    // 获取注解值
                    String name = fields[i].getAnnotation(ApiModelProperty.class).value();
                    return name;
                }
            }
        }
        return null;
    }

    /**
     * 根据字段获取注解值
     *
     * @param key
     * @param clazz
     * @return
     */
    public static String getNotes(String key, Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            // 除过fieldMap中的属性，其他属性都获取
            if (key.equals(fields[i].getName())) {
                boolean annotationPresent = fields[i].isAnnotationPresent(ApiModelProperty.class);
                if (annotationPresent) {
                    // 获取注解值
                    String notes = fields[i].getAnnotation(ApiModelProperty.class).notes();
                    return notes;
                }
            }
        }
        return null;
    }

    /**
     * 获取注解值
     *
     * @param clazz
     * @return
     */
    public static Map<String, String> getFieldsNotes(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < fields.length; i++) {
            boolean annotationPresent = fields[i].isAnnotationPresent(ApiModelProperty.class);
            if (annotationPresent) {
                // 获取注解值
                String notes = fields[i].getAnnotation(ApiModelProperty.class).notes();
                if (StrUtil.isNotBlank(notes)) {
                    map.put(fields[i].getName(), notes);
                }
            }
        }
        return map;
    }
}
